package com.sirun.ble.utils.sdk;

import static com.sirun.ble.constants.BleConfig.BleSdkTag;
import static com.sirun.ble.constants.BleConfig.DEFALUT_RESCAN_TIME;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanRecord;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.ParcelUuid;
import android.widget.Toast;

import com.sirun.ble.constants.BleConfig;
import com.sirun.ble.utils.AwByteUtil;
import com.sirun.ble.utils.AwDataUtil;
import com.sirun.ble.utils.AwLog;
import com.sirun.ble.utils.sdk.AwBleSpUtil;
import com.sirun.ble.utils.sec.AwAesUtil;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;


/**
 * @author : hzw
 */
@SuppressLint("MissingPermission")
public class AwBleUtil {

    private static BluetoothAdapter mBluetoothAdapter;

    public static String getBleTypeStr(BluetoothDevice device) {
        if(device == null) {
            return "未知蓝牙类型";
        }
        switch (device.getType()) {
            case BluetoothDevice.DEVICE_TYPE_UNKNOWN:
                return "未知蓝牙类型";
            case BluetoothDevice.DEVICE_TYPE_CLASSIC:
                return "经典蓝牙 Classic - BR/EDR devices";
            case BluetoothDevice.DEVICE_TYPE_LE:
                return "低功耗蓝牙 Low Energy - LE-only";
            case BluetoothDevice.DEVICE_TYPE_DUAL:
                return "多模蓝牙 Dual Mode - BR/EDR/LE";
        }
        return "未知蓝牙类型";
    }

    public static boolean isBleConnected(BluetoothDevice device) {
        if(device == null) {
            return false;
        }
        return BluetoothDevice.BOND_BONDED == device.getBondState();
    }

    public static String getBleConnectStr(BluetoothDevice device) {
        if (device == null) {
            return "未连接";
        }
        return "逻辑已修改.";
//        return BleManager.getInstance().isConnected() ? "已连接" : "未连接";
//        switch (device.getBondState()) {
//            case BluetoothDevice.BOND_BONDED:
//                return "已连接";
//            case BluetoothDevice.BOND_BONDING:
//                return "连接中";
//            case BluetoothDevice.BOND_NONE:
//                return "未连接";
//        }
//        return "未知";
    }

    /**
     * 判断是否有蓝牙功能模块
     */
    public static boolean checkBleIsSupport(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            //有蓝牙功能模块
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设备是否支持蓝牙  true为支持
     *
     * @return
     */
    public static boolean isSupportBlue(Context context) {
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        return mBluetoothAdapter != null;
    }

    /**
     * 自动打开蓝牙（异步：蓝牙不会立刻就处于开启状态）
     * 这个方法打开蓝牙不会弹出提示
     */
    public static void openBlueAsyn(Context context) {
        if (isSupportBlue(context)) {
            mBluetoothAdapter.enable();
        }
    }

    /**
     * 自动打开蓝牙（同步）
     * 这个方法打开蓝牙会弹出提示
     * 需要在onActivityResult 方法中判断resultCode == RESULT_OK  true为成功
     */
    public static void openBlueSync(Activity activity, int requestCode) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 检查GPS是否打开
     *
     * @return
     */
    public static boolean checkGPSIsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return false;
        }
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static int checkBleDevice(Context context) {
        //首先获取BluetoothManager
        BluetoothManager bluetoothManager =
                (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        //获取BluetoothAdapter
        if (bluetoothManager != null) {
            BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
            if (mBluetoothAdapter != null) {
                if (!mBluetoothAdapter.isEnabled()) {
                    //调用enable()方法直接打开蓝牙
                    return BleConfig.TAG_BLE_CLOSE;
                    //该方法也可以打开蓝牙，但是会有一个很丑的弹窗，可以自行尝试一下
                    //                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    //                    enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //                    startActivity(enableBtIntent);
                }
            } else {
                Toast.makeText(context, "手机不支持蓝牙", Toast.LENGTH_SHORT).show();
                return BleConfig.TAG_BLE_NO_SUPPORT;
            }
        }
        return BleConfig.TAG_BLE_OPEN;
    }

    /**
     * 强制开启当前 Android 设备的 Bluetooth
     *
     * @return true：强制打开 Bluetooth　成功　false：强制打开 Bluetooth 失败
     */
    public static boolean turnOnBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();

        if (bluetoothAdapter != null) {
            return bluetoothAdapter.enable();
        }

        return false;
    }

    public static List<BluetoothDevice> getPairedDevicesList() {
        List<BluetoothDevice> list = new ArrayList<>();
        // 获取BluetoothAdapter实例
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 确保蓝牙适配器已经初始化并且已经打开
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            // 获取所有已配对设备的集合
            Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
            // 遍历已配对设备
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    // 可以在这里获取设备名称、地址等信息
                    String deviceName = device.getName();
                    String deviceHardwareAddress = device.getAddress(); // 设备的MAC地址
                    AwLog.d(BleConfig.BleSdkTag, "getPairedDevicesList device: " + deviceName + " ,address: " + deviceHardwareAddress);
                    // 执行你需要的操作
                    list.add(device);
                }
            }
        } else {
            // 蓝牙适配器未启用或不可用
            AwLog.d(BleConfig.BleSdkTag, "getPairedDevicesList bluetoothAdapter error");
        }
        return list;
    }

    public static BluetoothDevice checkPariedBle(Context context) {
        List<BluetoothDevice> list = getPairedDevicesList();
        if(AwDataUtil.isEmpty(list)) {
            AwLog.d(BleConfig.BleSdkTag, "checkPariedBle paired is empty");
            return null;
        }
        if(AwDataUtil.isEmpty(AwBleSpUtil.getBleMac(context))) {
            AwLog.d(BleConfig.BleSdkTag, "checkPariedBle current mac is empty");
            return null;
        }
        for(BluetoothDevice device : list) {
            if(!AwDataUtil.isEmpty(device.getAddress()) && device.getAddress().equals(AwAesUtil.deFile(AwBleSpUtil.getBleMac(context)))) {
                return device;
            }
        }
        return null;
    }

    public static List<ParcelUuid> getDevicesUUIDList(BluetoothDevice device) {
        ParcelUuid[] uuidArrays = device.getUuids();
        if(uuidArrays == null) {
            AwLog.d(BleConfig.BleSdkTag, "getDeviceUUIDList is null, return");
            return new ArrayList<>();
        }
        AwLog.d(BleConfig.BleSdkTag, "getDeviceUUIDList is normal");
        return Arrays.asList(uuidArrays);
    }

    public static long getIntervalTime(Context context) {
        if(context == null) {
            return 0;
        }
        String lastTime = AwBleSpUtil.getBleDisconnectTime(context);
        if(AwDataUtil.isEmpty(lastTime)) {
            AwLog.d(BleSdkTag, "getIntervalTime lastTime is null, return 0");
            return 0;
        }
        long lastTimeLong = Long.parseLong(lastTime);
        long currentTime = System.currentTimeMillis();
        long result = (currentTime - lastTimeLong) / 1000;
        if(result >= DEFALUT_RESCAN_TIME) {
            AwLog.d(BleSdkTag, "getIntervalTime lastTime is above rescan time, return 0");
            return 0;
        } else {
            result = DEFALUT_RESCAN_TIME - result;
        }
        AwLog.d(BleSdkTag, "getIntervalTime time: " + result);
        return result * 1000;
    }

    @SuppressLint("WrongConstant")
    public static boolean isNetworkAvailable(Context var0) {
        ConnectivityManager var1;
        NetworkInfo var2;
        return (var1 = (ConnectivityManager)var0.getSystemService("connectivity")) != null && (var2 = var1.getActiveNetworkInfo()) != null && var2.isConnected() && var2.getState() == NetworkInfo.State.CONNECTED;
    }

    // 打印ScanRecord的方法
    public static String printScanRecord(ScanRecord scanRecord) throws UnsupportedEncodingException {
        if (scanRecord != null) {
            StringBuilder builder = new StringBuilder(1000);
            builder.append("Advertise Data:");
            byte[] data = scanRecord.getBytes();
            for (int i = 0; i < data.length; i++) {
                builder.append(String.format(" 0x%02X", data[i]));
            }
            builder.append("\n");

//            builder.append("Advertise Data as UTF-8: ");
//            builder.append(new String(data, "UTF-8"));
            builder.append("Advertise Data print: ");
            builder.append(AwByteUtil.printBytes(data));
            builder.append("\n");

            builder.append("Tx Power Level: ");
            builder.append(scanRecord.getTxPowerLevel());
            builder.append("\n");

            builder.append("Device Name: ");
            builder.append(scanRecord.getDeviceName());
            builder.append("\n");

            // 根据需要添加更多你感兴趣的信息
            // ...
            return builder.toString();
        } else {
            return "";
        }
    }
}
